/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.example.distschedule.slice;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.distschedule.ResourceTable;
import com.example.distschedule.bean.Command;
import com.example.distschedule.bean.DeviceResult;
import com.example.distschedule.bean.RespondBase;
import com.example.distschedule.event.MessageEvent;
import com.example.distschedule.rx2.OKHttpUtilsRx2;
import com.example.distschedule.toast.XToastUtils;
import com.example.distschedule.utils.CommandUtil;
import com.example.distschedule.utils.DeviceStateUtil;
import com.example.distschedule.utils.PreferencesUtil;
import com.socks.library.KLog;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Component;
import ohos.agp.components.Image;
import ohos.agp.components.Slider;
import ohos.agp.components.Text;
import ohos.app.dispatcher.TaskDispatcher;
import ohos.app.dispatcher.task.TaskPriority;
import ohos.miscservices.timeutility.Time;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import org.greenrobot.eventbus.EventBus;

import java.util.Locale;

import static com.example.distschedule.slice.SelectDeviceAbilitySlice.KEY_IS_SET_COMMAND;


public class AquaponicsAbilitySlice_expand extends AbilitySlice {

    private Text temperature;
    private Text humidity;
    private Text lux;
    private Text TDS;
    private Text CO2;
    private Text watertemp;
    private Text PH;

    private String deviceId;
    private boolean isOnActive = false;

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_Aquaponics_expand);
        deviceId = intent.getStringParam("deviceId");
        initComponents();
        initDeviceState();
    }

    private void initAquaponicsState() {
        TaskDispatcher globalTaskDispatcher = getGlobalTaskDispatcher(TaskPriority.DEFAULT);
        globalTaskDispatcher.asyncDispatch(() -> {
            KLog.i("async task initLampState run");
            getDeviceInfo();
        });
    }

    private void initDeviceState() {
        OKHttpUtilsRx2.INSTANCE.getApi().getDeviceInfo(deviceId, PreferencesUtil.getUserId(getContext()))
                .compose(OKHttpUtilsRx2.INSTANCE.ioMain())
                .subscribe(new OKHttpUtilsRx2.SubjectImpl<RespondBase<DeviceResult>>() {
                    @Override
                    public void onNext(RespondBase<DeviceResult> deviceInfo) {
                        KLog.i(deviceInfo);
                        if (deviceInfo.isSuccess() && deviceInfo.getResult().isOnline()) {// 更新状态
                            String property = deviceInfo.getResult().getProperty();
                            isOnActive = true;
                            temperature.setText(DeviceStateUtil.getTemperature(property));
                            humidity.setText(DeviceStateUtil.getHumidity(property));
                            TDS.setText(DeviceStateUtil.getTDS(property));
                            lux.setText(DeviceStateUtil.getLux(property));
                            CO2.setText(DeviceStateUtil.getCO2(property));
                            watertemp.setText(DeviceStateUtil.getWatertemp(property));
                            PH.setText(DeviceStateUtil.getPH(property));
                        } else {
                            initAquaponicsState();
                        }
                    }

                    @Override
                    public void onError(Throwable throwable) {
                        // 失败是因为首次配网状态未更新
                        initAquaponicsState();
                    }
                });
    }

    private void getDeviceInfo() {
        Time.sleep(10 * 1000);
        OKHttpUtilsRx2.INSTANCE.getApi().getDeviceInfo(deviceId, PreferencesUtil.getUserId(getContext()))
                .compose(OKHttpUtilsRx2.INSTANCE.ioMain())
                .subscribe(new OKHttpUtilsRx2.SubjectImpl<RespondBase<DeviceResult>>() {
                    @Override
                    public void onNext(RespondBase<DeviceResult> deviceInfo) {
                        super.onNext(deviceInfo);
                        KLog.i(deviceInfo);
                        if (deviceInfo.getResult() == null || !deviceInfo.getResult().isOnline()) {
                            XToastUtils.toast("未配网成功,请再次碰一碰重试");
                        }
                    }
                });
    }

    private void initComponents() {
        findComponentById(ResourceTable.Id_Aquaponics_img_left).setClickedListener(this::goBack);//退出

        temperature = (Text) findComponentById(ResourceTable.Id_Aquaponics_text_temperature);
        humidity = (Text) findComponentById(ResourceTable.Id_Aquaponics_text_humidity);
        lux = (Text) findComponentById(ResourceTable.Id_Aquaponics_text_light);
        TDS = (Text) findComponentById(ResourceTable.Id_Aquaponics_text_TDS);
        CO2 = (Text) findComponentById(ResourceTable.Id_Aquaponics_text_CO2);
        watertemp = (Text) findComponentById(ResourceTable.Id_Aquaponics_text_watertemp);
        PH = (Text) findComponentById(ResourceTable.Id_Aquaponics_text_PH);

        Image rightIcon = (Image) findComponentById(ResourceTable.Id_Aquaponics_img_right);
        rightIcon.setClickedListener(this::goInfo);
    }


    private void goBack(Component component) {
        onBackPressed();
    }

    private void goInfo(Component component) {
        XToastUtils.info("获取温度,湿度,光照强度,CO2,TDS,水温,PH值", 5000);
    }

    @Override
    public void onActive() {
        super.onActive();
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }
}